<template>
  <div style="position: relative">
    <el-input v-model="goodsName" clearable readonly placeholder="请选择商品" :style="'width: 100%; max-width: ' + maxWidth">
      <el-button slot="append" type="primary" @click="showDialog">点击选择</el-button>
    </el-input>
    <i v-if="goodsName" class="el-icon-error del" @click="clear" />
    <select-goods-dialog ref="dialog" :only-online="onlyOnline" :sku="sku" :store-id="storeId" @select="select" />
  </div>
</template>

<script>
import SelectGoodsDialog from '../SelectGoodsDialog/index'
export default {
  name: 'SelectGoods',
  components: { SelectGoodsDialog },
  props: {
    maxWidth: {
      type: String,
      default: '400px'
    },
    value: {
      type: [String, Number, Object, Array],
      default: undefined
    },
    sku: {
      type: Boolean,
      default: false
    },
    storeId: {
      type: [String, Number],
      default: null
    },
    onlyOnline: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      show: false,
      goodsName: null
    }
  },
  computed: {
    _value: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  watch: {
    value(newVal) {
      if (newVal) {
        if (newVal.goodsSkuNames && newVal.goodsSkuNames.length > 0) {
          this.goodsName = newVal.goodsName + '（' + newVal.goodsSkuNames + '）'
        } else {
          this.goodsName = newVal.goodsName
        }
      } else {
        this.goodsName = null
      }
      this._value = newVal
    }
  },
  methods: {
    showDialog() {
      const vm = this
      vm.$refs.dialog.show()
    },
    select(goods) {
      const vm = this
      console.log(goods)
      if (goods) {
        if (goods.goodsSkuNames && goods.goodsSkuNames.length > 0) {
          vm.goodsName = goods.goodsName + '（' + goods.goodsSkuNames + '）'
        } else {
          vm.goodsName = goods.goodsName
        }
        vm._value = goods
        vm.$emit('change', vm._value)
        vm.$forceUpdate()
      }
    },
    clear() {
      const vm = this
      vm._value = null
      vm.goodsName = null
      vm.$emit('change', vm._value)
    }
  }
}
</script>

<style lang="scss" scoped>

  ::v-deep .el-input-group__append {
    background-color: #1890ff;
    border-color: #1890ff;
    color: #FFFFFF;
  }

  .del {
    position: absolute;
    left: 268px;
    top: 0;
    color: #cccccc;
    font-size: 18px;
    padding: 9px;
    cursor: pointer;
  }

</style>
